#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QThread>
#include <QDesktopServices>
#include <QUrl>


LoginWindow::LoginWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::LoginWindow)
{
    ui->setupUi(this);

   QPropertyAnimation* animation = new QPropertyAnimation(this,"windowOpacity");
   animation->setDuration(500);//设置动画持续时间
   animation->setStartValue(0);
   animation->setEndValue(1);
   animation->start();//开始动画      参数：停止时删除



    this->setWindowFlags(Qt::FramelessWindowHint);

    ui->passwordLineEdit->setEchoMode(QLineEdit::Password);
    initAllInformation();



    connect(ui->loginButton,&QPushButton::clicked,this,&LoginWindow::login);
    connect(ui->quitButton,&QPushButton::clicked,this,[=](){
        QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity");
        animation->setDuration(500);
        animation->setStartValue(1);
        animation->setEndValue(0);
        animation->start();
        connect(animation,SIGNAL(finished()),this,SLOT(close()));
        delete ui;
    });

    connect(ui->homeButton,&QPushButton::clicked,this,&LoginWindow::home);
    connect(ui->contactsButton,&QPushButton::clicked,this,&LoginWindow::contacts);
    connect(ui->aboutUsButton,&QPushButton::clicked,this,&LoginWindow::aboutUs);
//    loadingDialog = new LoadingDialog(this);





}

LoginWindow::~LoginWindow()
{

    delete ui;
}

void LoginWindow::initAllInformation()
{
    qDebug()<<"初始化信息";
    QSettings settings("config.ini",QSettings::IniFormat);
    if(settings.value("section/Checked").toBool()){
        token = settings.value("section/token").toString();
        QString account_R = settings.value("section/account").toString();
        QString pass_word_R = settings.value("section/password").toString();
        ui->rememberInformationBox->setChecked(true);
        ui->accountLineEdit->setText(decodeInfo(account_R));
        ui->passwordLineEdit->setText(decodeInfo(pass_word_R));

    }
}

void LoginWindow::login()
{

//    loadingDialog->show();

    account = ui->accountLineEdit->text();
    password = ui->passwordLineEdit->text();

    if(account.isEmpty()||password.isEmpty())
    {
        QMessageBox::information(this,"错误","请填写完整账户或密码");
        return;
    }


    qDebug()<<"进行登录";
    QString note = "0";
    QString type = "步态分析";
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkRequest request;
    request.setUrl(QUrl(baseUrl+loginApi));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QString login = "username="+account+"&password="+password+"&note="+note+"&type="+type;
    QByteArray loginForm = login.toUtf8();
    reply =  manager->post(request,loginForm);
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT(slotError(QNetworkReply::NetworkError)));
    if(!reply->isRunning())QMessageBox::about(NULL,"登陆错误","后台没有启动");
    connect(reply,SIGNAL(readyRead()),this,SLOT(loginResult()));
    QEventLoop loop;
    connect(reply,SIGNAL(finished()),&loop,SLOT(quit()));


    loop.exec();
     delete reply;
    reply = nullptr;
     delete manager;
    manager = nullptr;

}

//（对网络请求中的json串进行登录信息判断）登陆结果
void LoginWindow::loginResult()
{
    QByteArray res = reply->readAll();
    qDebug()<<"网络请求的reply数据为"<<QString(res);
    QJsonDocument jsonDocument = QJsonDocument::fromJson(res);
    QJsonObject jsonObject = jsonDocument.object();
    int status = jsonObject.value("code").toInt();
    //将jsonObject中value类型为status的String字符串赋值给status
    qDebug()<<"status的数值为"<<status;

    if(status == 20000){
        token = jsonObject.value("data").toObject().value("token").toString();//将jsonObject中value类型为token的String字符串赋值给token
        qDebug()<<"token的数值为"<<token;

        QSettings settings("config.ini",QSettings::IniFormat);
        if(ui->rememberInformationBox->isChecked()){
            settings.beginGroup("section");
                qDebug()<<account<<password;
            settings.setValue("token","Bearer "+token);
            settings.setValue("account",encodeInfo(account));
            settings.setValue("password",encodeInfo(password));
            settings.setValue("Checked",true);
            settings.endGroup();

        }else{
           settings.clear();
           settings.beginGroup("section");
           settings.setValue("Checked",false);
           settings.endGroup();
        }


        bluetoothWideget = new BluetoothWideget;

        QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity");
         animation->setDuration(500);
         animation->setStartValue(1);
         animation->setEndValue(0);
         animation->start();
         QTest::qSleep(500);
        this->hide();
        bluetoothWideget->show();
//        QMessageBox::about(NULL,"成功","登陆成功");
//        emitToken(token);

    }else{
        QString msg = jsonObject.value("message").toString();
        QString info = "登录失败:" + QString::number(status) + msg;
        QMessageBox::about(NULL,"登陆错误",info);
    }

//    loadingDialog->hide();
    delete reply;
    reply = nullptr;

}







void LoginWindow::home()
{
    qDebug()<<"home";
    QDesktopServices::openUrl(QUrl(QString("http://121.36.217.102")));


}

void LoginWindow::contacts()
{
    qDebug()<<"contacts";
    QDesktopServices::openUrl(QUrl(QString("http://121.36.217.102/user")));
}

void LoginWindow::aboutUs()
{
    qDebug()<<"About us";
    QDesktopServices::openUrl(QUrl(QString("http://121.36.217.102")));
}



//加密编码
QString LoginWindow::encodeInfo(QString code)
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::CBC , QAESEncryption::PKCS7);
//----------------QString=>QByteArray----------------
    QByteArray input(code.toLocal8Bit());
    QByteArray key = aesKey.toLocal8Bit();
    QByteArray iv = aesIv.toLocal8Bit();
    QByteArray encodedString = encryption.encode(input, key, iv).toBase64();
    return QString(encodedString);
}
//加密解码
QString LoginWindow::decodeInfo(QString encode)
{
    QAESEncryption encryption(QAESEncryption::AES_128, QAESEncryption::CBC , QAESEncryption::PKCS7);
    //----------------QString=>QByteArray----------------
    QByteArray input(QByteArray::fromBase64(encode.toUtf8()));
    QByteArray key = aesKey.toLocal8Bit();
    QByteArray iv = aesIv.toLocal8Bit();
    QByteArray decodedString = encryption.decode(input, key, iv);
    QByteArray decoded = QAESEncryption::RemovePadding(decodedString,QAESEncryption::PKCS7);
    return QString(decoded);
}




void LoginWindow::on_close_clicked()
{

    QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity");
     animation->setDuration(500);
     animation->setStartValue(1);
     animation->setEndValue(0);
     animation->start();
     connect(animation, SIGNAL(finished()), this, SLOT(close()));
     delete ui;
}

void LoginWindow::slotError(QNetworkReply::NetworkError error)
{
    QMetaEnum meta = QMetaEnum::fromType<QNetworkReply::NetworkError>();
     QString info=meta.valueToKey(QString::number(error).toInt());
     switch(QString::number(error).toInt()){
     case 1:
         info = "后台未启动";
     break;
}
    QMessageBox::about(NULL,"登陆错误",info);
}
